import 'package:flutter/material.dart';
import '../service/service_method.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../routes/application.dart';
import './search_page/search_page.dart';
import '../drawer_page/Drawer.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provide/provide.dart';
import '../provide/setting.dart';
import '../provide/currentIndex.dart';
import 'package:cached_network_image/cached_network_image.dart';

class HomePage extends StatefulWidget {
  final Widget child;

  HomePage({Key key, this.child}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  int page = 1;
  var hotGoodsList = [];
  int popNum = 2;// 点击两次返回退出
  int _lastClickTime = 0;
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    Fluttertoast.showToast(
        msg: '注意！登录状态只保持两个小时',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 2,
        backgroundColor: Colors.pink,
        textColor: Colors.white,
        fontSize: 16.0
    );
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: _doubleExit,
      child: Scaffold(
        appBar: AppBar(
          title: Text('生活商城'),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.search),
              onPressed: (){
                Navigator.push(context, MaterialPageRoute(
                  builder: (context){
                    return SearchPage();
                  }
                ));
              },
            )
          ],
        ),
        drawer: DrawerPage(),
        body: FutureBuilder(
          future: getHomePageContent(),
          builder: (context,snapshot){
            if(snapshot.hasData){
              var data = json.decode(snapshot.data.toString());
              List swiperDataList = data['data']['slides'];// 轮播图
              List navigatorList = data['data']['category'];// 导航项
              if(navigatorList.length>10){
                navigatorList.removeRange(10, navigatorList.length);
              }
              String advertiesPicture = data['data']['advertesPicture']['PICTURE_ADDRESS'];// 广告图
              List recommendList = data['data']['recommend']; // 商品推荐
              String floor1Title =data['data']['floorName']['floor1'];//楼层1的标题图片
              String floor2Title =data['data']['floorName']['floor2'];//楼层1的标题图片
              String floor3Title =data['data']['floorName']['floor3'];//楼层1的标题图片
              List floor1 = data['data']['floor1']; //楼层1商品和图片 
              List floor2 = data['data']['floor2']; //楼层1商品和图片 
              List floor3 = data['data']['floor3']; //楼层1商品和图片
              List hotGoodsList = data['data']['hotGoods']; // 热卖商品
              return ListView(
                children: <Widget>[
                  SwiperDiy(swiperDataList: swiperDataList,),// 轮播图
                  TopNavigator(navigatorList: navigatorList,),
                  AdBanner(advertiesPicture:advertiesPicture),
                  Recommend(recommendList: recommendList,),
                  FloorTitle(picture_address:floor1Title),
                  FloorContent(floorGoodsList:floor1),
                  FloorTitle(picture_address:floor2Title),
                  FloorContent(floorGoodsList:floor2),
                  FloorTitle(picture_address:floor3Title),
                  FloorContent(floorGoodsList:floor3),
                  hotGoods(hotGoodsList:hotGoodsList),
                ],
              );
              
              }else {
              return Center(
                child: Text('加载中'),
              );
            }
          },
        )
      ),
    );
  }

  Future<bool> _doubleExit() {
    int nowTime = new DateTime.now().microsecondsSinceEpoch;
    if (_lastClickTime != 0 && nowTime - _lastClickTime > 1500) {
      return new Future.value(true);
    } else {
      Fluttertoast.showToast(
        msg: '双击退出应用',
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.BOTTOM,
        timeInSecForIos: 1,
        backgroundColor: Theme.of(context).primaryColor,
        textColor: Colors.white,
        fontSize: 16.0
    );
      _lastClickTime = new DateTime.now().microsecondsSinceEpoch;
      new Future.delayed(const Duration(milliseconds: 1500), () {
        _lastClickTime = 0;
      });
      return new Future.value(false);
    }
  }
}

// 首页轮播组件
class SwiperDiy extends StatelessWidget {
  final List swiperDataList;

  SwiperDiy({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(333),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemBuilder: (context,index){
          return InkWell(
            onTap: (){
              Application.router.navigateTo(context,"/detail?id=${swiperDataList[index]['ID']}");
            },
            child: Provide<SettingProvide>(
              builder: (context,child,val){
                return val.noImage?Image.asset('images/noImage.png',fit: BoxFit.fill,)
                                  :Image.network("${swiperDataList[index]['IMAGE1']}",fit: BoxFit.fill);
              },
            ),
          );
        },
        itemCount: swiperDataList.length,
        pagination: SwiperPagination(),
        autoplay: true,
      ),
    );
  }
}

// 首页导航部分
class TopNavigator extends StatelessWidget {
  final List navigatorList;

  TopNavigator({Key key, this.navigatorList}) : super(key: key);

  // 返回每一项导航元素
  Widget _gridViewItemUI(BuildContext context,item){
    return InkWell(
      onTap: (){
        Provide.value<CurrentIndexProvide>(context).changeIndex(1);
      },
      child: Column(
        children: <Widget>[
          Provide<SettingProvide>(
            builder: (context,child,val){
              return val.noImage?Image.asset('images/noImage.png',height: 40,)
                                :Image.network(item['image'],width: ScreenUtil().setWidth(95),);
            },
          ),
          Text(item['mallCategoryName'])
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(150),
      padding: EdgeInsets.all(3),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),// 禁用 gridView 的滚动，防止和首页火爆专区上拉加载冲突
        crossAxisCount: 5,
        padding: EdgeInsets.all(4),
        children: navigatorList.map((item){
          return _gridViewItemUI(context, item);
        }).toList()
      ),
    );
  }
}

// 广告部分
class AdBanner extends StatelessWidget {
  final String advertiesPicture;

  AdBanner({Key key, this.advertiesPicture}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Provide<SettingProvide>(
        builder: (context,child,val){
          return val.noImage?Center(child: Text('这是一个广告图'),)
                            :Image.network(advertiesPicture);
        },
      ),
    );
  }
}

// 商品推荐区域
class Recommend extends StatelessWidget {
  final List recommendList;

  Recommend({Key key, this.recommendList}) : super(key: key);



  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(420),
      margin: EdgeInsets.only(top: 10),
      child: Column(
        children: <Widget>[
          _titleWidget(context),
          _recommendList(context)
        ],
      )
    );
  }

  // 推荐商品标题
  Widget _titleWidget(context){
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10, 2, 0, 5),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(width: 0.5,color: Colors.black12)
        )
      ),
      child: Text('商品推荐',style: TextStyle(color: Theme.of(context).primaryColor),),
    );
  }

  Widget _recommendList(context){
    return Container(
      height: ScreenUtil().setHeight(360),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: recommendList.length,
        itemBuilder: (context,index){
          return _item(index,context);
        },
      ),
    );
  }

  Widget _item(index,context){
    return InkWell(
      onTap: (){
        Application.router.navigateTo(context,"/detail?id=${recommendList[index]['ID']}");
      },
      child: Container(
        height: ScreenUtil().setHeight(390),
        width: ScreenUtil().setWidth(250),
        padding: EdgeInsets.all(8),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            left: BorderSide(width: 0.5,color: Colors.black12)
          )
        ),
        child: Column(
          children: <Widget>[
            Provide<SettingProvide>(
              builder: (context,child,val){
                return val.noImage?Image.asset('images/noImage.png',height: 100,)
                                  :CachedNetworkImage(
                                    imageUrl: recommendList[index]['IMAGE1'],
                                    placeholder: (context, url) => Center(
                                      child: Text('正在加载',style: TextStyle(color: Colors.white),),
                                    ),
                                    errorWidget: (context, url, error){
                                      return Container(
                                        width: ScreenUtil().setWidth(123),
                                        height: ScreenUtil().setHeight(210),
                                        child: Icon(Icons.error),
                                      );
                                    },
                                    fit: BoxFit.contain,
                                  );
              },
            ),
            Text('${recommendList[index]['NAME']}',maxLines: 1,overflow: TextOverflow.ellipsis,style: TextStyle(color: Theme.of(context).primaryColor),),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text('￥${recommendList[index]['ORI_PRICE']}'),
                Text(
                  '￥${recommendList[index]['PRESENT_PRICE']}',
                  style: TextStyle(color: Colors.grey,decoration: TextDecoration.lineThrough),)
              ],
            )
          ],
        ),
      ),
    );
  }
}

// 楼层标题
class FloorTitle extends StatelessWidget {
  final String picture_address; // 图片地址

  FloorTitle({Key key, this.picture_address}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8),
      child: Text(picture_address,style: TextStyle(color: Theme.of(context).primaryColor),),
    );
  }
}

//楼层商品
class FloorContent extends StatelessWidget {
  final List floorGoodsList;

  FloorContent({Key key, this.floorGoodsList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    
    return Container(
      child: Column(
        children: <Widget>[
          _firstRow(context),
          _otherGoods(context)
        ],
      )
    );
  }

  // 返回每个商品图
  Widget _goodsItem(item,context){
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
      onTap: (){
        Application.router.navigateTo(context, "/detail?id=${item['ID']}");
      },
      child: Provide<SettingProvide>(
        builder: (context,child,val){
          return val.noImage?Image.asset('images/noImage.png')
                            :CachedNetworkImage(
                              imageUrl: item['IMAGE1'],
                              placeholder: (context, url) => Center(
                                child: Text('正在加载',style: TextStyle(color: Colors.white),),
                              ),
                              errorWidget: (context, url, error){
                                return Container(
                                  width: ScreenUtil().setWidth(375),
                                  height: ScreenUtil().setHeight(375),
                                  child: Icon(Icons.error),
                                );
                              },
                              fit: BoxFit.contain,
                            );
        },
      ),
    )
    );
  }
  // 第一层不规则商品部件
  Widget _firstRow(context){
    return Row(
      children: <Widget>[
        Column(
          children: <Widget>[
            _goodsItem(floorGoodsList[0],context),
            _goodsItem(floorGoodsList[1],context),
          ],
        ),
        Column(
          children: <Widget>[
            _goodsItem(floorGoodsList[2],context),
            _goodsItem(floorGoodsList[3],context)
          ],
        )
      ],
    );
  }

  // 两个规则商品
  Widget _otherGoods(context){
    return Row(
      children: <Widget>[
        _goodsItem(floorGoodsList[4],context),
        _goodsItem(floorGoodsList[5],context)
      ],
    );
  }
}

// 热卖商品
class hotGoods extends StatefulWidget {
  List hotGoodsList = [];

  hotGoods({Key key, this.hotGoodsList}) : super(key: key);

  _hotGoodsState createState() => _hotGoodsState();
}

class _hotGoodsState extends State<hotGoods> {
  @override
  Widget build(BuildContext context) {
    return Container(
       child: Column(
         children: <Widget>[
           hotTitle(),
           _wrapList()
         ],
       )
    );
  }

  // 热卖商品标题
  Widget hotTitle(){
    return Container(
      margin: EdgeInsets.only(top: 10),
      padding: EdgeInsets.all(5),
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(width: 0.5,color: Colors.black12)
        )
      ),
      child: Text('热卖商品',style: TextStyle(color: Theme.of(context).primaryColor),),
    );
  }

  // 热卖商品
  Widget _wrapList(){
    if(widget.hotGoodsList.isNotEmpty){
      List<Widget> listWidget = widget.hotGoodsList.map((item){
        return InkWell(
          onTap: (){
            Application.router.navigateTo(context,"/detail?id=${item['ID']}");
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5),
            margin: EdgeInsets.only(bottom: 3),
            child: Column(
              children: <Widget>[
                Provide<SettingProvide>(
                  builder: (context,child,val){
                    return val.noImage?Image.asset('images/noImage.png')
                                      :CachedNetworkImage(
                                        imageUrl: item['IMAGE1'],
                                        placeholder: (context, url) => Center(
                                          child: Text('正在加载',style: TextStyle(color: Colors.white),),
                                        ),
                                        errorWidget: (context, url, error){
                                          return Container(
                                            width: ScreenUtil().setWidth(370),
                                            height: ScreenUtil().setHeight(350),
                                            child: Icon(Icons.error),
                                          );
                                        },
                                        fit: BoxFit.contain,
                                      );
                  },
                  
                ),
                Text(
                  item['NAME'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Theme.of(context).primaryColor,fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Text('￥${item['ORI_PRICE']}'),
                    Text(
                     '￥${item['PRESENT_PRICE']}',
                     style: TextStyle(color: Colors.black26,decoration: TextDecoration.lineThrough), 
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();

      return Wrap(
        spacing: 2,
        children: listWidget
      );
    }else {
      return Text('上拉加载更多哦');
    }
  }
}